package com.xb.loan.cashier.biz.job;

import com.xb.loan.cashier.biz.service.CashierEncashOrderService;
import com.xb.loan.cashier.biz.task.TaskManagerFactory;
import com.xb.loan.cashier.biz.task.plat.PlatAccountEncashTask;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.util.DateHelper;
import com.xb.loan.util.StringUtils;
import com.xb.loan.util.qrtz.task.AbstractCronTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * 监控平台提现对账定时任务
 */
public class PlatAccountEncashJob extends AbstractCronTask {
    
    private static final Logger log = LoggerFactory.getLogger(PlatAccountEncashJob.class);

    /**
     * 1.创建账期内对账任务,任务名称以“任务类名_账期”命名
     * 2.创建账期外发生退票需要重新对账任务,任务名称以“任务类名_账期_时间戳”命名,
     * 同一账期可能重新对账多次要创建多个重新对账任务.
     *
     */
    @Override
    public void run() {
        CashierEncashOrderService cashierEncashOrderService = getSpringBean("cashierEncashOrderService");
        PlatAccountEncashTask paet = null;
        Date date = DateHelper.getBeforeDay(new Date(), -1);
        String accountPeriod = DateHelper.formatDate("yyyyMMdd", date);
        if (StringUtils.isEmpty(accountPeriod)) {
            log.info("run 账期为空,已退出!");
            return;
        }
        log.info("run 开始处理平台账期:"+accountPeriod+"数据");
        //启动当前账期对账任务
        paet = getSpringBean("platAccountEncashTask");
        paet.setAccountPeriod(accountPeriod);
        TaskManagerFactory.getTaskManager(ICashierEnumConst.TaskManagerCode.ACCTONT).addTask(paet);
        log.info("run 当前账期："+accountPeriod+"已启动提现对账任务");
        //查询当前账期外需要重新对账的账期
        int count = cashierEncashOrderService.queryRefundCount(accountPeriod);
        if (count>0) {
            List<String> list = cashierEncashOrderService.queryRefundAccountPeriod(accountPeriod);
            for (String ap : list) {//启动非当前账期需重新对账任务
                paet = getSpringBean("platAccountEncashTask");
                paet.setAccountPeriod(ap);
                TaskManagerFactory.getTaskManager(ICashierEnumConst.TaskManagerCode.ACCTONT).addTask(paet);
                log.info("run 账期："+ap+"已启动提现重新对账任务");
            }
        } else {
            log.info("run 当前账期："+accountPeriod+",没有找到需重新对账的账期");
        }
    }
    
}
